// 积分收银页面
import React, {Component} from 'react';
import ModalDropdown from 'react-native-modal-dropdown';

import {StatusBar,Text, View, TouchableWithoutFeedback, ScrollView, TouchableOpacity, StyleSheet, TextInput} from 'react-native';
import {Actions} from 'react-native-router-flux';
import Tips from 'react-native-root-tips';
import {is, fen_to_yuan, fen_money} from '../../../utils';

import CXIcon from '../../../style/icon/CXIcon';
import styles, {mainBackgroundColor, white} from "../../../style/global";

import storeActions from '../../../store/actions/store';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import memberActions from "../../../store/actions/member";
import Modal from 'react-native-modalbox';

class balanceCashPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            orderInfo: {
                user: {},
                order: {},
            },
            isCombination: false,  // 是否开启组合支付
            currentEdit: {
                key: 'cash_pay',
                name: '现金',
                value: '',
                active: true
            },  // 当前编辑的字段
            currentClerk: '',  // 当前导购
            init: false,
            actual: 0, // 实收 单位分
            remaining: 0, // 找零 单位分
            note:'',//备注
            payType: [
                {
                    key: 'cash_pay',
                    name: '现金',
                    value: 0,
                    active: true
                },
                {
                    key: 'wx_pub',
                    name: '微信',
                    value: 0,
                    active: false
                },
                {
                    key: 'ali_scan_pay',
                    name: '支付宝',
                    value: 0,
                    active: false
                },
                {
                    key: 'pop_cash_pay',
                    name: 'POS机',
                    value: 0,
                    active: false
                },
            ],
            keyBoardList: [
                {
                    value: 1,
                    type: 'num'
                },
                {
                    value: 2,
                    type: 'num'
                },
                {
                    value: 3,
                    type: 'num'
                },
                {
                    value: 50,
                    type: 'replace'
                },
                {
                    value: 4,
                    type: 'num'
                },
                {
                    value: 5,
                    type: 'num'
                },
                {
                    value: 6,
                    type: 'num'
                },
                {
                    value: 100,
                    type: 'replace'
                },
                {
                    value: 7,
                    type: 'num'
                },
                {
                    value: 8,
                    type: 'num'
                },
                {
                    value: 9,
                    type: 'num'
                },
                {
                    value: 200,
                    type: 'replace'
                },
                {
                    value: '00',
                    type: 'num'
                },
                {
                    value: 0,
                    type: 'num'
                },
                {
                    value: '.',
                    type: 'dot'
                },
                {
                    value: '备注',
                    type: 'note'
                }
            ]
        }
    }
    componentDidMount() {
        const {storeAction} = this.props;
        storage.load({
            key: 'balance-order-info'
        }).then(res => {
           if (res) {

               storeAction.getClerkList((res) => {
                   if (res && res.status && res.data) {
                       this.setState({
                           currentClerk: res.data[0]
                       });
                   }
               });

               let currentEdit = this.state.currentEdit;
               let payType = this.state.payType;
               currentEdit.value = res.order.pay_amount_yuan
               payType.forEach((item) => {
                   if (item.key == 'cash_pay') {
                       item.value = res.order.pay_amount_yuan
                   }
               });

               console.log(res);
               this.setState({
                   orderInfo: res,
                   init: true,
                   payType: payType,
                   currentEdit: currentEdit,
                   actual: res.order.pay_amount,
                   remaining: 0
               })

           } else {
               Tips.showFail('订单数据错误');
               setTimeout(() => {
                   Actions.reset('IndexPage');
               }, 1500);
           }
        }).catch(err => {
            Tips.showFail('订单数据错误');
            setTimeout(() => {
                Actions.reset('IndexPage');
            }, 1500);
        });
    }

    // 支付方式Node
    _payTypeNode() {
        return this.state.payType.map((item, index) => {
            return (
                <Text style={[style.typeItem, item.active ? style.typeActive : '']} key={index} onPress={() => this._selectPayType(item, index)}>{item.name}</Text>
            )
        })
    }
    // 支付方式输入Node
    _payTypeInputNode() {

        return this.state.payType.map((item, index) => {
            if (item.active) {
                return (
                    <View style={style.itemLeft} key={index}>
                        <View style={{marginRight: 20}}>
                            <Text>{item.name}： </Text>
                        </View>
                        <View>
                            <Text style={[style.bigText, {color: '#202020'}]}>￥
                                <Text onPress={() => this._selectValuePayType(item)} style={[this.state.currentEdit.key == item.key ? style.currentEdit : '']}>
                                    {item.value}
                                </Text>
                            </Text>
                        </View>
                    </View>
                )
            }
        })
    }
    // 键盘左侧NODE
    _keyBoardNode() {
        return this.state.keyBoardList.map((item, index) => {
            return(
                <TouchableOpacity style={style.keyItemBox} key={index} onPress={() => this._keyBoardDown(item)}>
                    <View >
                        <Text style={style.keyItem}>{item.value}</Text>
                    </View>
                </TouchableOpacity>
            )
        })
    }

    // 导购列表NODE
    _clerkNode(option, index, isSelected) {
        return (
            <Text style={{padding: 5}}>
                {option.name}
            </Text>
        );
    }

    // 导购显示文本
    _clerkTextNode(option) {
        return option.name;
    }

    // 选择导购
    _selectClerk(index, item) {
        if (item) {
            this.setState({
                currentClerk: item
            })
        }
    }

    // 改变组合支付
    _changeCombination() {
        const combination = this.state.isCombination;
        let currentEdit = this.state.currentEdit;

        let payType = this.state.payType;
        if (!combination) {
            payType.forEach((item) => {
                item.active = false;
                if (item.key == 'cash_pay') {
                    item.active = true;
                    item.value = (this.state.orderInfo.order.pay_amount / 100).toFixed(2);
                }
                if (item.key == 'wx_pub') {
                    item.active = true;
                    item.value = 0;
                }
            });
        } else {
            payType.forEach((item) => {
                if (item.key == 'cash_pay') {
                    item.active = true;
                    item.value = (this.state.orderInfo.order.pay_amount / 100).toFixed(2);

                } else {
                    item.active = false;
                    item.value = 0

                }
            });


        }
        currentEdit = {
            key: 'cash_pay',
            name: '现金',
            value: '',
            active: true
        };
        currentEdit.value = (this.state.orderInfo.order.pay_amount / 100).toFixed(2);
        this.setState({
            payType: payType,
            currentEdit: currentEdit,
            isCombination: !this.state.isCombination
        });
        this._payTypeNode();
    }
    // 选择支付方式
    _selectPayType(item, index) {
        const combination = this.state.isCombination;
        let isOn = true;
        let oneValue = 0;
        let towValue = 0;
        if (!combination) {
            let payType = this.state.payType;
            payType.forEach((items) => {

                if (items.key == item.key) {
                    items.active = true;
                    items.value = Number((this.state.orderInfo.order.pay_amount / 100).toFixed(2));
                } else {
                    items.active = false;
                    items.value = 0;
                }
            });
            this.setState({
                payType: payType,
                currentEdit: item,
                actual: this.state.orderInfo.order.pay_amount,
                remaining: 0,
            })
        } else {
            if (item.active) return;

            let payType = this.state.payType;
            for (let items of payType) {
                if (items.active) {
                    if (isOn) {
                        oneValue = items.value;
                        items.active = false;
                        items.value = 0;
                    } else {
                        towValue = items.value;
                        items.value = oneValue;
                    }
                    isOn = false;
                }
                if (items.key == item.key) {
                    items.active = true;
                    items.value = towValue;
                }
            }
            this.setState({
                payType: payType,
                currentEdit: item,
                actual: this.state.orderInfo.order.pay_amount,
                remaining: 0,
            })
        }
    }
    _selectValuePayType(item) {
        this.setState({
            currentEdit: item
        })
    }

    // 键盘按下
    _keyBoardDown(item) {
        const type = item.type;
        const value = item.value;
        const currentEdit = this.state.currentEdit;
        const isCombination = this.state.isCombination;
        const pay_amount = this.state.orderInfo.order.pay_amount;

        let payType = this.state.payType;
        let actual = this.state.actual;
        let remaining = this.state.remaining;
        if(item.type == 'note'){
            this._changeShowModal();
            return
        }
        // 没有开启组合支付
            if (currentEdit.key == 'cash_pay') {
                payType.forEach((pay, index) => {
                    if (pay.key == currentEdit.key) {
                        const val = this._formatMoney(item, pay.value || '');
                        console.log(val);
                        pay.value = val;
                        currentEdit.value = val;
                        actual = Math.signFigures(val * 100);
                        remaining = Math.signFigures(val * 100) - pay_amount;
                        console.log(Math.signFigures(val * 100) - pay_amount);


                        if (isCombination) {
                            payType.forEach(items => {
                                if (items.key != currentEdit.key && items.active) {
                                    actual += Math.signFigures(items.value * 100);
                                }
                            });
                            remaining = actual - pay_amount;
                        }
                    }
                })
                console.log('现金支付');
            } else {
                console.log('其他支付');
                payType.forEach((pay, index) => {
                    if (pay.key == currentEdit.key) {
                        const val = this._formatMoney(item, pay.value || '');
                        console.log('多少呀', val);
                        if (Number(Math.signFigures(val * 100)) > pay_amount) {
                            Tips.showFail('不能大于实收金额');

                            pay.value = (pay_amount/ 100).toFixed(2);
                            currentEdit.value = (pay_amount / 100).toFixed(2);
                        } else {
                            pay.value = val;
                            currentEdit.value = val;


                            if (isCombination) {
                                payType.forEach(items => {
                                    if (items.key != currentEdit.key && items.active) {
                                        items.value = ((pay_amount  - Math.signFigures(val * 100)) / 100).toFixed(2);
                                    }
                                });
                                actual = pay_amount
                                remaining = 0;
                            }
                        }



                    }
                })
            }

        this.setState({
            payType: payType,
            actual: actual,
            remaining: remaining,
            currentEdit: currentEdit,
        })
    }
    // 处理输入的值
    _formatMoney(item,values) {
        const type = item.type;
        const value = item.value;
        if (type == 'replace') {
            values = String(value)
        } else if (type != 'note') {
            if (value === '00') {
                if (values.indexOf('.') == -1) {
                    values = String(values) + String(value);
                }
            } else {
                values = String(values) + String(value);
                values = values.replace(/[^\d\.]|^\./g, '').replace(/\.{2}/g, '.').replace(/^([1-9]\d*|0)(\.\d{1,2})(\.|\d{1})?$/, '$1$2').replace(/^0\d{1}/g, '0');
            }
        }
        return values
    }
    // 删除值
    _deleteMoney() {
        const currentEdit = this.state.currentEdit;
        const isCombination = this.state.isCombination;
        const pay_amount = this.state.orderInfo.order.pay_amount;

        let payType = this.state.payType;
        let actual = this.state.actual;
        let remaining = this.state.remaining;
        if (!currentEdit.value) return;

        let newVal = String(currentEdit.value).substr(0, String(currentEdit.value.length - 1));

        payType.forEach((pay, index) => {
            if (pay.key == currentEdit.key) {
                pay.value = newVal || 0;
                currentEdit.value = newVal || 0;
                if (currentEdit.key == 'cash_pay') {
                    actual = Math.signFigures(newVal * 100);
                    remaining = Math.signFigures(newVal * 100) - pay_amount
                }
                if (isCombination) {
                    payType.forEach(items => {
                        if (items.key != currentEdit.key && items.active) {
                            actual += Math.signFigures(items.value * 100);
                        }
                    });
                    remaining = actual - pay_amount;
                }
            }
        });

        if (isCombination && currentEdit.key != 'cash_pay') {
            payType.forEach(items => {
                if (items.key != currentEdit.key && items.active) {
                    items.value = ((pay_amount - Math.signFigures(newVal * 100)) / 100).toFixed(2);
                }
            });
        }

        this.setState({
            payType: payType,
            actual: actual,
            remaining: remaining,
            currentEdit: currentEdit,
        })
    }
    _changeShowModal(){
        this.refs.showModal.open()
    }
    _changeCloseModal(){
        this.refs.showModal.close()
    }


    // 提交订单
    _confirmOrder() {
        let data = {
            actual: Number(this.state.actual),  // 实收
            remaining: this.state.remaining, // 找零
            order_no: this.state.orderInfo.order.order_no, // 订单编号
            total_amount: Number(this.state.orderInfo.order.pay_amount),  // 订单总额
            clerk_id: this.state.currentClerk.id,  // 导购id
            note: '', // 备注
            input_pay_amount: 0,  // 已经输入了的支付总额
            payments: []
        };
        this.state.payType.forEach((item => {
            if (item.active) {
                item.amount = Math.signFigures(item.value * 100);
                data.input_pay_amount += item.amount;
                data.payments.push(item);
            }
        }));

        if (data.input_pay_amount < this.state.orderInfo.order.pay_amount) {
            Tips.showFail('支付金额不足')
        } else if (!this.state.currentClerk) {
            Tips.showFail('请选择导购');
        } else {
            const {storeAction} = this.props;
            storeAction.confirmBalanceOrder(data, (res) => {
                if (res && res.status) {
                    storage.remove({
                        key: 'balance-order-info'
                    });
                    Actions.reset('BalanceSuccessPage', {
                        order_no: res.data.order.order_no
                    })
                }
            });
        }
    }

    render() {
        const { storeState } = this.props;
        return (
            <View>
                <StatusBar hidden={true} />
                <View style={style.body}>
                    <View style={style.orderInfoBox}>
                        <View style={style.orderInfo}>
                            <View style={style.infoItem}>
                                <View style={style.itemLeft}>
                                    <View style={{marginRight: 40}}>
                                        <Text>会员：{this.state.orderInfo.user.nick_name} {this.state.orderInfo.user.mobile}</Text>
                                    </View>
                                    <View>
                                        <Text>余额： {fen_to_yuan(this.state.orderInfo.balance)}</Text>
                                    </View>
                                </View>
                                <View style={style.itemRight}>
                                    <Text>
                                        导购员：
                                    </Text>
                                    <View style={style.dropDownBox}>
                                        <ModalDropdown style={style.dropDown} textStyle={{color: '#909090', fontSize: 14}} defaultValue={this.state.currentClerk ? this.state.currentClerk.name : '请选择导购员呀'} options={storeState.clerkList} renderRow={(option, index, isSelected) => this._clerkNode(option, index, isSelected)} renderButtonText={(option) => this._clerkTextNode(option)} onSelect={(index, item) => this._selectClerk(index, item)}>

                                        </ModalDropdown>
                                        <CXIcon name='xiala' size={10} color={'#909090'}>

                                        </CXIcon>
                                    </View>
                                </View>
                            </View>

                            <View style={style.infoItem}>
                                <View style={style.itemLeft}>
                                    <View style={{marginRight: 20}}>
                                        <Text>总额：</Text>
                                    </View>
                                    <View>
                                        <Text style={[style.bigText]}>￥{fen_to_yuan(this.state.orderInfo.order.pay_amount)}</Text>
                                    </View>
                                </View>
                                <View style={style.itemRight}>
                                    <TouchableWithoutFeedback>
                                        <Text style={style.wipe}>
                                            {this.state.orderInfo.order.balance_title}
                                        </Text>
                                    </TouchableWithoutFeedback>
                                </View>
                            </View>
                            <View style={style.infoItem}>
                                <View style={style.itemLeft}>
                                    <View style={{marginRight: 20}}>
                                        <Text>实收： </Text>
                                    </View>
                                    <View>
                                        <Text style={[style.bigText, {color: '#202020'}]}>￥
                                            <Text>
                                                {fen_to_yuan(this.state.actual)}
                                            </Text>
                                        </Text>
                                    </View>
                                </View>
                                <View style={style.itemRight}>
                                    <View style={{marginRight: 20}}>
                                        <Text>找零： </Text>
                                    </View>
                                    <View>
                                        <Text style={[style.bigText, {color: '#202020'}]}>￥{fen_to_yuan(this.state.remaining)}</Text>
                                    </View>
                                </View>
                            </View>
                            <View style={style.infoItem}>
                                {this._payTypeInputNode()}
                            </View>
                            <View style={style.payType}>

                                <Text  onPress={() => this._changeCombination()} style={[style.typeItem, this.state.isCombination ? style.comType : '']}>组合支付</Text>
                                {this._payTypeNode()}
                            </View>
                        </View>
                    </View>
                    <View style={style.keyboardBox}>
                        <View style={style.keyboard}>
                           <View style={style.keyboardLeft}>
                               {this._keyBoardNode()}
                           </View>
                            <View style={style.keyboardRight}>
                                <TouchableOpacity style={[style.rightItem ,style.icon]} onPress={() => this._deleteMoney()}>
                                    <CXIcon name='shanchu' size={20} color={white}>

                                    </CXIcon>
                                </TouchableOpacity>

                                <TouchableOpacity style={[style.rightItem, {backgroundColor: '#4B8AF2'}]} onPress={() => this._confirmOrder()}>
                                    <View>
                                        <Text style={[style.submit]}>
                                            确定
                                        </Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                    <View>
                        <Modal ref="showModal"
                               position="center"
                               backdropColor='black'
                               style={{backgroundColor:'transparent', width:660,justifyContent:'center'}}
                               coverScreen={true}
                               swipeToClose={false}
                               backdropOpacity={0.6}
                        >
                            <View style={style.modalBox}>
                                <View style={style.modalBody}>
                                    <View style={style.modalBodyLastItem}>
                                        <Text style={style.modalTxt}>备注</Text>
                                        <TextInput style={style.modalLastInput}
                                                   multiline={true}
                                                   textAlignVertical={'top'}
                                                   onChangeText={(note) =>this.setState({note})}
                                        />
                                    </View>

                                </View>
                                <View style={style.modalBtn}>
                                    <TouchableOpacity onPress={() => this._changeCloseModal()}>
                                        <Text style={style.sureBtn}>确认</Text>
                                    </TouchableOpacity>

                                </View>

                            </View>
                        </Modal>
                    </View>
                </View>
            </View>
        )
    }
}

const style = StyleSheet.create({
    body: {
        // marginTop: 20,
    },
    modalBox:{
        backgroundColor:'#fff',
        borderRadius:4
    },
    modalBody:{
        paddingLeft:30,
        paddingBottom:100,
        borderBottomWidth:1,
        borderBottomColor:'#DBDBDB'
    },
    modalBodyItem:{
        flexDirection:'row',
        alignItems:'center',
        height:90,
        borderBottomColor:'#D8D8D8',
        borderBottomWidth:1
    },
    modalBodyLastItem:{
        flexDirection:'row',
        paddingTop:28,
        paddingRight:60
    },
    modalTxt:{
        color:'#4A4A4A',
        fontSize:16,
        paddingRight: 56
    },
    modalInput:{
        flex:1,
        fontSize:18,
        color:'#4B8AF2'
    },
    modalSelectItem:{
        width:'100%',
        padding:10

    },
    modalIcon:{
        paddingRight:60
    },
    modalLastInput:{
        color:'#333333',
        fontSize:16,
        lineHeight:23,
        paddingHorizontal:30,
        paddingVertical: 16,
        borderWidth:1,
        borderColor:'#D7D7D7',
        backgroundColor:'#F3F3F3',
        borderRadius:4,
        height:90,
        flex:1
    },
    modalBtn:{
        height:90,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center'
    },
    sureBtn:{
        width:160,
        height:44,
        lineHeight:44,
        textAlign:'center',
        backgroundColor:mainBackgroundColor,
        borderRadius:4,
        color:"#fff",
        fontSize:18,
    },
    orderInfoBox: {
      alignItems: 'center',
        backgroundColor: white,
        paddingBottom: 6,
        height: '61%'
    },
    orderInfo: {
        width: 900,
    },
    infoItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 10,
        paddingVertical: 22,
        borderBottomWidth: 1,
        borderColor: '#F0F0F5'
    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1
    },
    itemRight: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1
    },
    dropDownBox: {
        backgroundColor: '#F3F3F3',
        height: 44,
        width: 240,
        borderRadius: 4,
      flexDirection: 'row',
      alignItems: 'center',
        paddingRight: 12
    },
    dropDown: {
        // flex: 1,
        width: 210,
        paddingLeft: 12
    },
    bigText: {
        fontSize: 22,
        color: mainBackgroundColor,
    },

    currentEdit: {
      color: white,
      backgroundColor: '#4B8AF2'
    },
    payType: {
        flexDirection: 'row',
        paddingVertical: 20
    },
    typeItem: {
        borderWidth: 1,
        borderColor: '#909090',
        width: 100,
        textAlign: 'center',
        lineHeight: 40,
        marginRight: 20,
    },
    wipe: {
        backgroundColor: mainBackgroundColor,
        borderRadius: 4,
        color: white,
        width: 100,
        lineHeight: 40,
        textAlign: 'center'
    },
    comType: {
        borderColor: mainBackgroundColor,
        color: mainBackgroundColor
    },
    typeActive: {
        backgroundColor: mainBackgroundColor,
        borderColor: mainBackgroundColor,
        color: '#ffffff'
    },
    keyboardBox: {
        height: '39%',
        // flex: 1,
        backgroundColor: '#202020',
        alignItems: 'center'
    },
    keyboard: {
        flexDirection: 'row',
        width: 720,
        height: '100%',
        // flex: 1,

        // height: 100,
        backgroundColor: '#0c0c0c',

    },
    keyboardLeft: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        flex: 1,
        paddingHorizontal: 4
    },
    keyboardRight: {
        width: 150
    },
    keyItemBox: {
        padding: 4,
        width: '25%',
    },
    keyItem:{
        textAlign: 'center',
        backgroundColor: '#494949',
        color: white,
        borderRadius: 4,
        lineHeight: 56,
        fontSize: 24
    },
    rightItem: {
        backgroundColor: '#494949',
        marginTop: 4,
        marginBottom: 4,
        marginRight: 8,
        textAlign: 'center',
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 4,
    },
    icon: {
        height: 56
    },
    submit: {
        lineHeight: 183,
        color: white,
        fontSize: 24,
    }

});

export default connect(state => ({
    storeState: state.store
}), dispatch => ({
    storeAction: bindActionCreators(storeActions, dispatch)
}))(balanceCashPage)
